// ignore_for_file: unused_element, non_constant_identifier_names

/*
 * @Author: CodeHare
 * @Date: 2023-10-30 11:34:54
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-23 17:27:51
 * @Description: EMS参数设置之电池设置
 */
import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/ems_params_setting_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/battery_set_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_set_interface.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';
import '../../../../../../../../components/log_utils.dart';

// ignore: must_be_immutable
class BatterySetWidget extends StatefulWidget {
  /// 设备ID
  String deviceId;

  BatterySetWidget(this.deviceId, {super.key});

  @override
  State<BatterySetWidget> createState() => _BatterySetWidgetState();
}

class _BatterySetWidgetState extends State<BatterySetWidget> {
  EmsParamsSettingController paramsSetController =
      Get.find<EmsParamsSettingController>();
  var batteryEnableSetList = BatterySetModel().batteryEnableSetList;
  var batteryProtectionParameterList =
      BatterySetModel().batteryProtectionParameterList;

  /// 电池系统使能设置请求参数
  late SettingReqParams requestParams;
  late Map<String, dynamic> batterySysEnableInput = {
    "EnableBatterySystemSelfStartFunction": "",
  };

  /// 电池系统保护参数设置请求参数
  late Map<String, dynamic> batteryProtectionInput = {
    "maxAllowableChargingVoltage": 0.0,
    "overVoltageErrorClearDifference": 0.0,
    "minAllowableChargingVoltage": 0.0,
    "lowVoltageErrorClearDifference": 0.0,
    "maxAllowableTemperature": 0.0,
    "overTempErrorClearDifference": 0.0,
    "minAllowableTemp": 0.0,
    "lowTempErrorClearDifference": 0.0,
    "maxAllowableVoltageOfBatteryPack": 0.0,
    "overVoltageErrorDifferenceOfBatteryPack": 0.0,
    "maxAllowableChargingCurrentOfBatteryPack": 0.0,
    "maxAllowableDischargeCurrentOfBatteryPack": 0.0,
    "generalOvervoltageLimit": 0.0,
    "severeOvervoltageLimit": 0.0,
    "generalUndervoltageLimit": 0.0,
    "severeUndervoltageLimit": 0.0,
    "generalChargingCurrentLimit": 0.0,
    "severeChargingCurrentLimit": 0.0,
    "generalDischargeCurrentLimit": 0.0,
    "severeDischargeCurrentLimit": 0.0,
    "generalOverTemperatureLimit": 0.0,
    "severeOverTemperatureLimit": 0.0,
    "generalLowTemperatureLimit": 0.0,
    "severeLowTemperatureLimit": 0.0,
  };

  /// 激活模块
  bool editEnabled = false;
  bool editProtection = false;
  bool activeSubmit = false;

  /// 弹窗相关
  final String ENABLED = ResKey.thingsEnable.tr;
  final String FORBIDDEN = ResKey.thingsDisable.tr;
  String hintText = "";
  int selectedIndex = 0;
  var conditions = <String>[ResKey.thingsEnable.tr, ResKey.thingsDisable.tr];

  /// 允许下发指令
  bool allowSend = false;

  /// 网络状态
  ConnectStatusType? connectStatus = ConnectStatusType.off;

  /// 订阅在线状态数据流
  UseSubsribe emsOnlineStatusSubsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsOnlineStatusSubscription;
  late Stream<Map<String, dynamic>> emsOnlineStatusBroadcastStream;

  /// 订阅指令值数据流
  UseSubsribe emsValSubscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsValSubscription;
  late Stream<Map<String, dynamic>> emsValBroadcastStream;
  late Map socketMap = {};

  @override
  void initState() {
    super.initState();

    _initBatterySysEnabledList();
    _initBatterySysProtectionParamsList();

    _listenEmsOnlineStatusValue();
    _listenEmsControlValue();
  }

  /// 监听EMS设备在线状态
  void _listenEmsOnlineStatusValue() {
    emsOnlineStatusBroadcastStream = emsOnlineStatusSubsribe
        .start([int.parse(widget.deviceId)], true,
            type: MessageEventType.networkStatus)
        .stream
        .asBroadcastStream();

    emsOnlineStatusSubscription = emsOnlineStatusBroadcastStream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
          $ConnectStatusTypeEnumMap,
          data['networkStatus'],
        );
      }
    });
  }

  /// 监听EMS指令值
  void _listenEmsControlValue() {
    emsValBroadcastStream = emsValSubscribe
        .start([int.parse(widget.deviceId)], true)
        .stream
        .asBroadcastStream();

    showLoading(toast: ResKey.loading.tr);
    emsValSubscription = emsValBroadcastStream.listen(
      (data) {
        socketMap = data;
        if (editEnabled || editProtection) return;
        Log.d("交流器设置是不是能编辑====$editEnabled====$editProtection");

        socketMap.forEach(
          (key, value) {
            String originData = value.toString();

            if (key == 'EnableBatterySystemSelfStartFunction') {
              Log.d("====电池$key的值========$originData");
              if (originData == "0") {
                batteryEnableSetList[1].previousValue =
                    batteryEnableSetList[1].value = ENABLED;
              } else if (originData == "1") {
                batteryEnableSetList[1].previousValue =
                    batteryEnableSetList[1].value = FORBIDDEN;
              } else {
                batteryEnableSetList[1].previousValue =
                    batteryEnableSetList[1].value = "socket值有误";
              }
            } else if (key == 'maxAllowableChargingVoltage') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[1].textEditingController!.text =
                  batteryProtectionParameterList[1].previousValue = originData;
            } else if (key == 'overVoltageErrorClearDifference') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[2].textEditingController!.text =
                  batteryProtectionParameterList[2].previousValue = originData;
            } else if (key == 'minAllowableChargingVoltage') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[3].textEditingController!.text =
                  batteryProtectionParameterList[3].previousValue = originData;
            } else if (key == 'lowVoltageErrorClearDifference') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[4].textEditingController!.text =
                  batteryProtectionParameterList[4].previousValue = originData;
            } else if (key == 'maxAllowableTemperature') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[5].textEditingController!.text =
                  batteryProtectionParameterList[5].previousValue = originData;
            } else if (key == 'overTempErrorClearDifference') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[6].textEditingController!.text =
                  batteryProtectionParameterList[6].previousValue = originData;
            } else if (key == 'minAllowableTemp') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[7].textEditingController!.text =
                  batteryProtectionParameterList[7].previousValue = originData;
            } else if (key == 'lowTempErrorClearDifference') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[8].textEditingController!.text =
                  batteryProtectionParameterList[8].previousValue = originData;
            } else if (key == 'maxAllowableVoltageOfBatteryPack') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[9].textEditingController!.text =
                  batteryProtectionParameterList[9].previousValue = originData;
            } else if (key == 'overVoltageErrorDifferenceOfBatteryPack') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[10].textEditingController!.text =
                  batteryProtectionParameterList[10].previousValue = originData;
            } else if (key == 'maxAllowableChargingCurrentOfBatteryPack') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[11].textEditingController!.text =
                  batteryProtectionParameterList[11].previousValue = originData;
            } else if (key == 'maxAllowableDischargeCurrentOfBatteryPack') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[12].textEditingController!.text =
                  batteryProtectionParameterList[12].previousValue = originData;
            } else if (key == 'generalOvervoltageLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[13].textEditingController!.text =
                  batteryProtectionParameterList[13].previousValue = originData;
            } else if (key == 'severeOvervoltageLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[14].textEditingController!.text =
                  batteryProtectionParameterList[14].previousValue = originData;
            } else if (key == 'generalUndervoltageLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[15].textEditingController!.text =
                  batteryProtectionParameterList[15].previousValue = originData;
            } else if (key == 'severeUndervoltageLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[16].textEditingController!.text =
                  batteryProtectionParameterList[16].previousValue = originData;
            } else if (key == 'generalChargingCurrentLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[17].textEditingController!.text =
                  batteryProtectionParameterList[17].previousValue = originData;
            } else if (key == 'severeChargingCurrentLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[18].textEditingController!.text =
                  batteryProtectionParameterList[18].previousValue = originData;
            } else if (key == 'generalDischargeCurrentLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[19].textEditingController!.text =
                  batteryProtectionParameterList[19].previousValue = originData;
            } else if (key == 'severeDischargeCurrentLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[20].textEditingController!.text =
                  batteryProtectionParameterList[20].previousValue = originData;
            } else if (key == 'generalOverTemperatureLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[21].textEditingController!.text =
                  batteryProtectionParameterList[21].previousValue = originData;
            } else if (key == 'severeOverTemperatureLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[22].textEditingController!.text =
                  batteryProtectionParameterList[22].previousValue = originData;
            } else if (key == 'generalLowTemperatureLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[23].textEditingController!.text =
                  batteryProtectionParameterList[23].previousValue = originData;
            } else if (key == 'severeLowTemperatureLimit') {
              Log.d("====电池$key的值========$originData");
              batteryProtectionParameterList[24].textEditingController!.text =
                  batteryProtectionParameterList[24].previousValue = originData;
            }
          },
        );

        dismissLoading();
        setState(() {});
      },
    );
  }

  /// 初始化电池使能参数值
  void _initBatterySysEnabledList() {
    batteryEnableSetList[1].value =
        batteryEnableSetList[1].previousValue = ResKey.pleSelect.tr;
  }

  /// 初始化电池保护参数值
  void _initBatterySysProtectionParamsList() {
    batteryProtectionParameterList[1].textEditingController!.text =
        batteryProtectionParameterList[1].previousValue = "";

    batteryProtectionParameterList[2].textEditingController!.text =
        batteryProtectionParameterList[2].previousValue = "";

    batteryProtectionParameterList[3].textEditingController!.text =
        batteryProtectionParameterList[3].previousValue = "";

    batteryProtectionParameterList[4].textEditingController!.text =
        batteryProtectionParameterList[4].previousValue = "";

    batteryProtectionParameterList[5].textEditingController!.text =
        batteryProtectionParameterList[5].previousValue = "";

    batteryProtectionParameterList[6].textEditingController!.text =
        batteryProtectionParameterList[6].previousValue = "";

    batteryProtectionParameterList[7].textEditingController!.text =
        batteryProtectionParameterList[7].previousValue = "";

    batteryProtectionParameterList[8].textEditingController!.text =
        batteryProtectionParameterList[8].previousValue = "";

    batteryProtectionParameterList[9].textEditingController!.text =
        batteryProtectionParameterList[9].previousValue = "";

    batteryProtectionParameterList[10].textEditingController!.text =
        batteryProtectionParameterList[10].previousValue = "";

    batteryProtectionParameterList[11].textEditingController!.text =
        batteryProtectionParameterList[11].previousValue = "";

    batteryProtectionParameterList[12].textEditingController!.text =
        batteryProtectionParameterList[12].previousValue = "";

    batteryProtectionParameterList[13].textEditingController!.text =
        batteryProtectionParameterList[13].previousValue = "";

    batteryProtectionParameterList[14].textEditingController!.text =
        batteryProtectionParameterList[14].previousValue = "";

    batteryProtectionParameterList[15].textEditingController!.text =
        batteryProtectionParameterList[15].previousValue = "";

    batteryProtectionParameterList[16].textEditingController!.text =
        batteryProtectionParameterList[16].previousValue = "";

    batteryProtectionParameterList[17].textEditingController!.text =
        batteryProtectionParameterList[17].previousValue = "";

    batteryProtectionParameterList[18].textEditingController!.text =
        batteryProtectionParameterList[18].previousValue = "";

    batteryProtectionParameterList[19].textEditingController!.text =
        batteryProtectionParameterList[19].previousValue = "";

    batteryProtectionParameterList[20].textEditingController!.text =
        batteryProtectionParameterList[20].previousValue = "";

    batteryProtectionParameterList[21].textEditingController!.text =
        batteryProtectionParameterList[21].previousValue = "";

    batteryProtectionParameterList[22].textEditingController!.text =
        batteryProtectionParameterList[22].previousValue = "";

    batteryProtectionParameterList[23].textEditingController!.text =
        batteryProtectionParameterList[23].previousValue = "";

    batteryProtectionParameterList[24].textEditingController!.text =
        batteryProtectionParameterList[24].previousValue = "";
  }

  /// 点击参数配置
  void _clickParamsSetting(index) {
    if (connectStatus == ConnectStatusType.off) return;
    activeSubmit = true;

    if (index == 1) {
      editEnabled = true;
      editProtection = false;
    } else {
      editProtection = true;
      editEnabled = false;
    }
    setState(() {});
  }

  /// 展示隐藏下发参数按钮
  void _showHiddenButton() {
    activeSubmit = false;
    editEnabled = false;
    editProtection = false;
    setState(() {});
  }

  /// 下发失败撤销赋值参数
  void _restoreBatteryEnableSetList() {
    batteryEnableSetList[1].value = batteryEnableSetList[1].previousValue;

    setState(() {});
  }

  /// 下发失败撤销赋值参数
  void _restoreBatteryProParamsList() {
    batteryProtectionParameterList[1].textEditingController!.text =
        batteryProtectionParameterList[1].previousValue;

    batteryProtectionParameterList[2].textEditingController!.text =
        batteryProtectionParameterList[2].previousValue;

    batteryProtectionParameterList[3].textEditingController!.text =
        batteryProtectionParameterList[3].previousValue;

    batteryProtectionParameterList[4].textEditingController!.text =
        batteryProtectionParameterList[4].previousValue;

    batteryProtectionParameterList[5].textEditingController!.text =
        batteryProtectionParameterList[5].previousValue;

    batteryProtectionParameterList[6].textEditingController!.text =
        batteryProtectionParameterList[6].previousValue;

    batteryProtectionParameterList[7].textEditingController!.text =
        batteryProtectionParameterList[7].previousValue;

    batteryProtectionParameterList[8].textEditingController!.text =
        batteryProtectionParameterList[8].previousValue;

    batteryProtectionParameterList[9].textEditingController!.text =
        batteryProtectionParameterList[9].previousValue;

    batteryProtectionParameterList[10].textEditingController!.text =
        batteryProtectionParameterList[10].previousValue;

    batteryProtectionParameterList[11].textEditingController!.text =
        batteryProtectionParameterList[11].previousValue;

    batteryProtectionParameterList[12].textEditingController!.text =
        batteryProtectionParameterList[12].previousValue;

    batteryProtectionParameterList[13].textEditingController!.text =
        batteryProtectionParameterList[13].previousValue;

    batteryProtectionParameterList[14].textEditingController!.text =
        batteryProtectionParameterList[14].previousValue;

    batteryProtectionParameterList[15].textEditingController!.text =
        batteryProtectionParameterList[15].previousValue;

    batteryProtectionParameterList[16].textEditingController!.text =
        batteryProtectionParameterList[16].previousValue;

    batteryProtectionParameterList[17].textEditingController!.text =
        batteryProtectionParameterList[17].previousValue;

    batteryProtectionParameterList[18].textEditingController!.text =
        batteryProtectionParameterList[18].previousValue;

    batteryProtectionParameterList[19].textEditingController!.text =
        batteryProtectionParameterList[19].previousValue;

    batteryProtectionParameterList[20].textEditingController!.text =
        batteryProtectionParameterList[20].previousValue;

    batteryProtectionParameterList[21].textEditingController!.text =
        batteryProtectionParameterList[21].previousValue;

    batteryProtectionParameterList[22].textEditingController!.text =
        batteryProtectionParameterList[22].previousValue;

    batteryProtectionParameterList[23].textEditingController!.text =
        batteryProtectionParameterList[23].previousValue;

    batteryProtectionParameterList[24].textEditingController!.text =
        batteryProtectionParameterList[24].previousValue;

    setState(() {});
  }

  /// 使能禁用值的转化
  String _formatSetValue(String value) {
    return value == ENABLED ? "0" : "1";
  }

  /// 赋值电池设置系统使能当前选择参数
  void _assignEnabledParams() {
    batterySysEnableInput['EnableBatterySystemSelfStartFunction'] =
        _formatSetValue(batteryEnableSetList[1].value);
  }

  /// 赋值电池设置电池保护参数设置当前选择参数
  void _assignProtectionParams() {
    batteryProtectionInput["maxAllowableChargingVoltage"] = double.parse(
        batteryProtectionParameterList[1].textEditingController!.text);
    batteryProtectionInput["overVoltageErrorClearDifference"] = double.parse(
        batteryProtectionParameterList[2].textEditingController!.text);
    batteryProtectionInput["minAllowableChargingVoltage"] = double.parse(
        batteryProtectionParameterList[3].textEditingController!.text);
    batteryProtectionInput["lowVoltageErrorClearDifference"] = double.parse(
        batteryProtectionParameterList[4].textEditingController!.text);

    batteryProtectionInput["maxAllowableTemperature"] = double.parse(
        batteryProtectionParameterList[5].textEditingController!.text);
    batteryProtectionInput["overTempErrorClearDifference"] = double.parse(
        batteryProtectionParameterList[6].textEditingController!.text);
    batteryProtectionInput["minAllowableTemp"] = double.parse(
        batteryProtectionParameterList[7].textEditingController!.text);
    batteryProtectionInput["lowTempErrorClearDifference"] = double.parse(
        batteryProtectionParameterList[8].textEditingController!.text);
    batteryProtectionInput["maxAllowableVoltageOfBatteryPack"] = double.parse(
        batteryProtectionParameterList[9].textEditingController!.text);

    batteryProtectionInput["overVoltageErrorDifferenceOfBatteryPack"] =
        double.parse(
            batteryProtectionParameterList[10].textEditingController!.text);
    batteryProtectionInput["maxAllowableChargingCurrentOfBatteryPack"] =
        double.parse(
            batteryProtectionParameterList[11].textEditingController!.text);
    batteryProtectionInput["maxAllowableDischargeCurrentOfBatteryPack"] =
        double.parse(
            batteryProtectionParameterList[12].textEditingController!.text);
    batteryProtectionInput["generalOvervoltageLimit"] = double.parse(
        batteryProtectionParameterList[13].textEditingController!.text);
    batteryProtectionInput["severeOvervoltageLimit"] = double.parse(
        batteryProtectionParameterList[14].textEditingController!.text);
    batteryProtectionInput["generalUndervoltageLimit"] = double.parse(
        batteryProtectionParameterList[15].textEditingController!.text);
    batteryProtectionInput["severeUndervoltageLimit"] = double.parse(
        batteryProtectionParameterList[16].textEditingController!.text);
    batteryProtectionInput["generalChargingCurrentLimit"] = double.parse(
        batteryProtectionParameterList[17].textEditingController!.text);
    batteryProtectionInput["severeChargingCurrentLimit"] = double.parse(
        batteryProtectionParameterList[18].textEditingController!.text);
    batteryProtectionInput["generalDischargeCurrentLimit"] =
        batteryProtectionParameterList[19].textEditingController!.text;
    batteryProtectionInput["severeDischargeCurrentLimit"] = double.parse(
        batteryProtectionParameterList[20].textEditingController!.text);
    batteryProtectionInput["generalOverTemperatureLimit"] = double.parse(
        batteryProtectionParameterList[21].textEditingController!.text);
    batteryProtectionInput["severeOverTemperatureLimit"] = double.parse(
        batteryProtectionParameterList[22].textEditingController!.text);
    batteryProtectionInput["generalLowTemperatureLimit"] = double.parse(
        batteryProtectionParameterList[23].textEditingController!.text);
    batteryProtectionInput["severeLowTemperatureLimit"] = double.parse(
        batteryProtectionParameterList[24].textEditingController!.text);
  }

  /// 收集指令下发参数
  Map<String, dynamic>? _collectInstructParams() {
    requestParams = SettingReqParams(
      deviceId: widget.deviceId,
      input: editEnabled ? batterySysEnableInput : batteryProtectionInput,
    );

    if (editEnabled) {
      return EnableBatterySystemSelfStartFunction().trigger(
        widget.deviceId,
        requestParams,
      );
    }

    return BatteryProtectionParameterSettings().trigger(
      widget.deviceId,
      requestParams,
    );
  }

  /// 表单校验
  void _validate(list) {
    if (list.length == 0) allowSend = false;

    if (editEnabled) {
      for (var i = 1; i < list.length; i++) {
        if (list[i].value.isEmpty) {
          allowSend = false;
          return;
        }
      }
    } else {
      for (var i = 1; i < list.length; i++) {
        if (list[i].textEditingController.text.isEmpty) {
          allowSend = false;
          return;
        }
      }
    }

    allowSend = true;
    setState(() {});
  }

  /// 表单校验失败
  void _validateFailure() {
    showError('请填写所有必填选项');
    // showDialog<void>(
    //   context: context,
    //   barrierDismissible: true,
    //   builder: (BuildContext dialogContext) {
    //     return BrnDialog(
    //       messageText: "请完成系统使能设置",
    //     );
    //   },
    // );

    // Future.delayed(
    //   const Duration(milliseconds: 1000),
    //   () => Get.back(),
    // );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  /// 确认参数下发警告框
  void _showConfirmSendDialog() {
    BrnDialogManager.showConfirmDialog(
      context,
      title: ResKey.deviceParameterSetting.tr,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      message: ResKey.deviceWhetherExecuteCurrentParameter.tr, // "是否立即执行参数下发",
      onConfirm: () {
        // ignore: prefer_typing_uninitialized_variables
        var params;

        /// 参数
        if (allowSend) {
          if (editEnabled) {
            _assignEnabledParams();
            params = _collectInstructParams();
          } else {
            _assignProtectionParams();
            params = _collectInstructParams();
          }

          var currentActive = editEnabled ? true : false;

          /// 下发指令
          paramsSetController.sendCommand(context, params).then(
            (value) {
              if (value == null) {
                currentActive
                    ? _restoreBatteryEnableSetList()
                    : _restoreBatteryProParamsList();
              }
            },
          );

          _showHiddenButton();
          Get.back();
        }
      },
      onCancel: () {
        editEnabled
            ? _restoreBatteryProParamsList()
            : _restoreBatteryEnableSetList();

        _showHiddenButton();
        Get.back();
      },
    );
  }

  /// 使能弹窗展示
  void _showEnabledDialog(context, item, index) {
    if (batteryEnableSetList[index].value == ENABLED) {
      selectedIndex = 0;
    } else {
      selectedIndex = 1;
    }
    showDialog(
      context: context,
      builder: (_) => StatefulBuilder(
        builder: (context, state) {
          return BrnSingleSelectDialog(
              isClose: true,
              title: ResKey.deviceEnableSettings.tr,
              conditions: conditions,
              checkedItem: conditions[selectedIndex],
              submitText: ResKey.sure.tr,
              onItemClick: (BuildContext context, int index) {
                hintText = conditions[index];
                selectedIndex = index;
              },
              onSubmitClick: (data) {
                setState(() {
                  batteryEnableSetList[index].value = conditions[selectedIndex];
                });
              });
        },
      ),
    );
  }

  Container _generateListHeader(item, moduleIndex) {
    return Container(
      height: 53,
      padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
      alignment: Alignment.center,
      color: Colour.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            item.label,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colour.mainTextColor,
            ),
          ),
          GestureDetector(
            onTap: () => _clickParamsSetting(moduleIndex),
            child: Text(
              editEnabled || editProtection ? "" : item.value,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colour.primaryColor,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _enabledSetting(context, item, index) {}

  @override
  Widget build(BuildContext context) {
    return GetBuilder<EmsParamsSettingController>(
      builder: (_) => Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    /// 系统使能模块
                    editProtection
                        ? Container()
                        : Container(
                            margin: const EdgeInsets.only(top: 10),
                            height: 103,
                            child: ListView.separated(
                              padding: EdgeInsets.zero,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                final item = batteryEnableSetList[index];

                                if (index == 0) {
                                  return _generateListHeader(item, 1);
                                }

                                return GestureDetector(
                                  onTap: () {
                                    if (editEnabled) {
                                      _showEnabledDialog(context, item, index);
                                    }
                                  },
                                  child: Container(
                                    height: 50,
                                    padding: EdgeInsets.only(
                                      left: editEnabled ? 6.w : 16.w,
                                      right: 16.w,
                                    ),
                                    color: Colour.white,
                                    alignment: Alignment.center,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        editEnabled
                                            ? Padding(
                                                padding: EdgeInsets.only(
                                                  right: 2.w,
                                                ),
                                                child: Text(
                                                  "*",
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    color:
                                                        Colour.warningTextColor,
                                                    fontSize: 14.sp,
                                                  ),
                                                ),
                                              )
                                            : const SizedBox(),
                                        Expanded(
                                          child: Text(
                                            item.label,
                                            style: TextStyle(
                                              color: Colour.lightTextColor,
                                              fontSize: 14.sp,
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.end,
                                            children: <Widget>[
                                              Padding(
                                                padding:
                                                    EdgeInsets.only(right: 7.w),
                                                child: Text(
                                                  textAlign: TextAlign.end,
                                                  item.value.isEmpty
                                                      ? ""
                                                      : item.value,
                                                  style: TextStyle(
                                                    color: connectStatus ==
                                                            ConnectStatusType
                                                                .off
                                                        ? Colour.hintTextColor
                                                        : Colour.mainTextColor,
                                                  ),
                                                ),
                                              ),
                                              Visibility(
                                                visible: editEnabled,
                                                child: Icon(
                                                  Icons.arrow_forward_ios,
                                                  size: 12.sp,
                                                  color: Colour.hintTextColor,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                              separatorBuilder:
                                  (BuildContext context, int index) => Divider(
                                color: Colour.dividerColor,
                                height: 1,
                                indent: 16.w,
                                endIndent: 16.w,
                              ),
                              itemCount: batteryEnableSetList.length,
                            ),
                          ),

                    /// 电池保护参数设置模块
                    editEnabled
                        ? Container()
                        : Container(
                            height: 1280,
                            color: Colour.white,
                            margin: const EdgeInsets.only(top: 10, bottom: 10),
                            child: ListView.separated(
                              physics: const NeverScrollableScrollPhysics(),
                              padding: EdgeInsets.zero,
                              itemBuilder: (context, index) {
                                final item =
                                    batteryProtectionParameterList[index];

                                if (index == 0) {
                                  return _generateListHeader(item, 2);
                                }

                                return GestureDetector(
                                  onTap: () {},
                                  child: ItemWidget(
                                    item.label,
                                    isRequired: editProtection,
                                    isCanEdit: editProtection,
                                    titleColor: Colour.lightTextColor,
                                    inputTextWidth: 170,
                                    item.textEditingController!,
                                    unitString: item.value,
                                    isShowDivider: true,
                                    titleFont: 14.sp,
                                    unitTextColor:
                                        connectStatus == ConnectStatusType.off
                                            ? Colour.offlineTextColor
                                            : Colour.mainTextColor,
                                    inputTextColor:
                                        connectStatus == ConnectStatusType.off
                                            ? Colour.offlineTextColor
                                            : Colour.mainTextColor,
                                  ),
                                );
                              },
                              separatorBuilder:
                                  (BuildContext context, int index) => Divider(
                                color: Colour.dividerColor,
                                height: 1,
                                indent: 16.w,
                                endIndent: 16.w,
                              ),
                              itemCount: batteryProtectionParameterList.length,
                            ),
                          ),
                  ],
                ),
              ),
            ),

            /// 下发按钮取消按钮
            Visibility(
              visible: activeSubmit,
              child: Align(
                alignment: Alignment.bottomCenter,
                child: YtBrnBottomButtonPanel(
                  mainButtonName: "下发参数",
                  mainButtonOnTap: () {
                    if (editEnabled) {
                      /// 校验参数
                      _validate(
                        editEnabled
                            ? batteryEnableSetList
                            : batteryProtectionParameterList,
                      );

                      if (allowSend) {
                        _showConfirmSendDialog();
                      } else {
                        _validateFailure();
                      }
                    } else {
                      _validate(
                        editProtection
                            ? batteryProtectionParameterList
                            : batteryEnableSetList,
                      );

                      if (allowSend) {
                        _showConfirmSendDialog();
                      } else {
                        _validateFailure();
                      }
                    }
                  },
                  secondaryButtonName: ResKey.cancel.tr,
                  secondaryButtonBorder: Border.all(
                    color: Colour.dividerColor,
                  ),
                  secondaryButtonOnTap: () {
                    editEnabled
                        ? _restoreBatteryEnableSetList()
                        : _restoreBatteryProParamsList();

                    _showHiddenButton();
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  dispose() {
    emsOnlineStatusSubscription?.cancel();
    emsOnlineStatusSubsribe.closeListen();
    emsValSubscription?.cancel();
    emsValSubscribe.closeListen();
    super.dispose();
  }
}
